﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web.Mvc;
using log4net;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.MatrixCloudApi;

namespace Matrix.MaKaYunShang.WeChat.Controllers
{
    /// <summary>
    /// 码云卡接口CONTROLLER
    /// </summary>
    public class MkysController : BaseInterfaceController
    {
        private readonly ILog _fileLog = LogManager.GetLogger(typeof (MkysController));

        #region Actions
        /// <summary>
        /// 公众号微信接口入口
        /// </summary>
        /// <returns></returns>
        public ActionResult WxInterface()
        {
            if (Request.Url == null)
            {
                return View();
            }

            var nWxInterfaceUrlIndex = Request.RawUrl.IndexOf("/WxInterface", StringComparison.Ordinal);
            var strPjCode = Request.RawUrl.Substring(1, nWxInterfaceUrlIndex-1);

#if DEBUG
            _fileLog.Info("MkysController | WxInterface Request " + Request.Url.AbsoluteUri);
#endif

            #region 验证签名分支
            var wxSignatureToken = ConfigurationManager.AppSettings["MkysSignatureToken"];
            var result  = CheckSingatureProcess(strPjCode, wxSignatureToken);
            if (result != null)
            {
                return result;
            }
            #endregion

            try
            {
#if DEBUG
                _fileLog.Info("MkysController | WxInterface Event Request" +
                              System.Web.HttpContext.Current.Request.InputStream);
#endif
                //获取当前云迈云中心项目资料
                var pjResult = GetCurrentMatrixCloudProjectInfo(strPjCode);
                if (!pjResult.Status)
                {
                    return View();
                }
                
                string strMsgType;
                string strJsonContent;

                //分析微信服务端POST到接口的数据，并获取公众号信息
                var wechatInfo = AnalysisWxPostData(out strMsgType, out strJsonContent);
                if (wechatInfo == null || wechatInfo.Id == 0)
                {
                    return View();
                }

                //根据MsgType调用分支处理流程
                //根据微信开发WIKI，保证在五秒内处理并回复，采用直接SUCCESS
                var strReplayXmlContent = "success";
                switch (strMsgType.ToLower())
                {
                    case "event":
                        strReplayXmlContent = WxEventProcess(strJsonContent, wechatInfo);
                        break;
                    case "text":
                    case "image":
                    case "voice":
                    case "video":
                    case "shortvideo":
                    case "location":
                    case "link":
                        strReplayXmlContent = WxMsgProcess(strJsonContent, wechatInfo);
                        break;
                }
#if DEBUG
                _fileLog.Info("MkysController | WxInterface : Return message content - " + strReplayXmlContent);
#endif
                if (!string.IsNullOrWhiteSpace(strReplayXmlContent))
                {
                    Response.ContentType = "text/xml";
                    Response.Write(strReplayXmlContent);
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysController | WxInterface : Exception - " + ex.Message + ex.StackTrace);
            }

            return View();
        }

        /// <summary>
        /// 公众号签名验证
        /// </summary>
        /// <param name="signatureToken"></param>
        /// <param name="signature"></param>
        /// <param name="timestamp"></param>
        /// <param name="nonce"></param>
        /// <param name="echostr"></param>
        /// <returns></returns>
        public ActionResult CheckSignature(string signatureToken, string signature, string timestamp, string nonce,
            string echostr)
        {
            var strResult = CheckSignatureFunc(signatureToken, signature, timestamp, nonce, echostr);

            ViewBag.PostValue = strResult;

            return View();
        }

        /// <summary>
        /// 微信登录验证回调接口，处理完毕并跳回验证前提供的回调地址
        /// </summary>
        /// <returns></returns>
        public ActionResult WxAuthUserToken()
        {
            string strRedirectUrl;

            var nWxInterfaceUrlIndex = Request.RawUrl.IndexOf("/WxAuthUserToken", StringComparison.Ordinal);
            var strPjCode = Request.RawUrl.Substring(1, nWxInterfaceUrlIndex - 1);
            //获取当前云迈云中心项目资料
            var pjResult = GetCurrentMatrixCloudProjectInfo(strPjCode);
            if (!pjResult.Status)
            {
                return View();
            }

            var wechatUserInfo = WxAuthUserTokenFunc(out strRedirectUrl);
            if (wechatUserInfo != null && wechatUserInfo.Id > 0)
            {
                AddNewConusmerInfo(wechatUserInfo);
            }

            if (!string.IsNullOrWhiteSpace(strRedirectUrl))
            {
                Response.Redirect(strRedirectUrl);
            }

            return View();
        }

        /// <summary>
        /// 第三方登录验证接口
        /// </summary>
        /// <param name="callBackUrlEncode"></param>
        /// <returns></returns>
        public ActionResult WxOAutherize(string callBackUrlEncode)
        {

            var nWxInterfaceUrlIndex = Request.RawUrl.IndexOf("/WxOAutherize", StringComparison.Ordinal);
            var strPjCode = Request.RawUrl.Substring(1, nWxInterfaceUrlIndex - 1);
            //获取当前云迈云中心项目资料
            var pjResult = GetCurrentMatrixCloudProjectInfo(strPjCode);
            if (!pjResult.Status)
            {
                return View();
            }

            var strAuthUrl = WxOAutherizeFunc(callBackUrlEncode);
            if (!string.IsNullOrWhiteSpace(strAuthUrl))
            {
                Response.Redirect(strAuthUrl);
            }
            return View();
        }
        #endregion

        #region Private Methods


        /// <summary>
        /// 处理微信上行的消息逻辑
        /// </summary>
        /// <param name="weChatMsgRev"></param>
        /// <param name="wechatInfo"></param>
        /// <returns></returns>
        public override string DealMsg(MxApiWeChatMsgRev weChatMsgRev, MxApiWechatInfo wechatInfo)
        {
            //根据微信开发WIKI，保证在五秒内处理并回复，采用直接SUCCESS
            const string strDefaultMsg = "success";
            if (wechatInfo == null || string.IsNullOrWhiteSpace(wechatInfo.AppId) ||
                string.IsNullOrWhiteSpace(wechatInfo.Secret))
            {
                _fileLog.Error("MkysController | DealMsg | None WechatMp Info - ");
                return strDefaultMsg;
            }

            if (weChatMsgRev == null)
            {
                _fileLog.Error("MkysController | DealMsg | Received message is empty");
                return strDefaultMsg;
            }

#if DEBUG
            _fileLog.Info("MkysController | DealMsg : received message content - " + weChatMsgRev.MsgId);
#endif

            try
            {
                var resultReply =  MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 1,
                    CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                if (!resultReply.Status)
                {
                    resultReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 0,
                        CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                    if (!resultReply.Status)
                    {
                        return string.Empty;
                    }
                }
                return resultReply.Data;
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysController | DealMsg : Exception - " + ex.Message + ex.StackTrace);
                
            }
            return string.Empty;
        }

        /// <summary>
        /// 处理微信上行的事件逻辑
        /// </summary>
        /// <param name="wechatEventHistory"></param>
        /// <param name="wechatInfo"></param>
        /// <returns></returns>
        public override string DealEvent(MxApiWechatEventHistory wechatEventHistory, MxApiWechatInfo wechatInfo)
        {
#if DEBUG
            _fileLog.Info("MkysController | DealEvent Begin - " + wechatEventHistory.Event);
#endif

            var strRetContent = string.Empty;

            switch (wechatEventHistory.Event.ToLower())
            {
                case "subscribe": //关注
                    strRetContent = SubscribeUser(wechatEventHistory, wechatInfo, 0);
                    break;
                case "unsubscribe": //取消订阅
                    UnsubscribeUser(wechatEventHistory, wechatInfo);
                    break;
                case "scan": //用户已关注时的事件推送
                    if (!string.IsNullOrWhiteSpace(wechatEventHistory.EventKey) &&
                        !string.IsNullOrWhiteSpace(wechatEventHistory.Ticket))
                    {
                        strRetContent = SubscribeUser(wechatEventHistory, wechatInfo, 1);
                    }
                    break;
                
                case "location": //上报地理位置事件
                    AddNewLoctationInfo(wechatEventHistory, wechatInfo);
                    strRetContent = string.Empty;
                    break;
                case "click": //自定义菜单事件
                case "view": //点击菜单跳转链接时的事件推送
                case "card_pass_check"://卡券通过审核
                case "card_not_pass_check"://卡券未通过审核
                case "user_get_card"://用户领取卡券
                case "user_del_card"://用户删除卡券
                case "user_consume_card"://核销事件
                case "User_pay_from_pay_cell"://微信买单事件
                case "user_view_card": //进入会员卡事件推送
                case "user_enter_session_from_card"://用户从卡券进入公众号会话
                case "card_pay_order": //券点流水详情事件(朋友的券)
                    //var wechatCardEntries = new WechatCardEntries(wechatEventHistory, wechatInfo);
                    //wechatCardEntries.CardEventProccess();
                    //break;
                case "masssendjobfinish": //群发事件推送群发结果
                    strRetContent = string.Empty;
                    break;
                default:
                    var weChatMsgRev = new MxApiWeChatMsgRev
                    {
                        FromUserName = wechatEventHistory.FromUserName,
                        MsgType = "text"
                    };
                    var resultReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 0,
                        CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                    if (resultReply.Status)
                    {
                        strRetContent = resultReply.Data;
                    }
                    else
                    {
                        strRetContent = string.Empty;
                    }
                    break;
            }

            return strRetContent;
        }

        /// <summary>
        /// 取消关注处理逻辑
        /// </summary>
        /// <param name="wechatEvent"></param>
        /// <param name="wechatInfo"></param>
        public override void UnsubscribeUser(MxApiWechatEventHistory wechatEvent, MxApiWechatInfo wechatInfo)
        {
            var userOpenId = wechatEvent.FromUserName;

            try
            {
                var wechatUserResult = MatrixCloudCenterInterFuncBllObj.GetWechatUserInfo(userOpenId,
                    CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                if (!wechatUserResult.Status || wechatUserResult.Data == null || wechatUserResult.Data.Id <= 0 ||
                    string.IsNullOrWhiteSpace(wechatUserResult.Data.OpenId))
                {
                    _fileLog.Error(
                        "MkysController | UnsubscribeUser : Cannot get wechat user info from Matrix-Cloud-Center - " +
                        wechatUserResult.Message);
                    return;
                }
                var wechatUser = wechatUserResult.Data;

                wechatUser.Subscribe = false;
                wechatUser.UnSubscribeTime = DateTime.Now;

                var result = MatrixCloudCenterInterFuncBllObj.UpdateWechatInfoUserToMatrixCloud(wechatUser,
                    CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);

#if DEBUG
                _fileLog.Info("MkysController | UnsubscribeUser : Update user subscribe status to unsubscribe - " +
                              wechatEvent.FromUserName);
#endif
                if (result.Status)
                {
                    //取消关注解绑用户
                    var consumerBll = new ConsumerBLL();
                    var consumerInfo = consumerBll.GetConsumerInfoByMxWechatInfoUserId(wechatUser.WiuId);
                    if (consumerInfo != null && consumerInfo.Id > 0)
                    {
                        consumerInfo.ShopId = 0;
                        consumerInfo.ShopAccountId = 0;
                        consumerBll.Update(consumerInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysController | UnsubscribeUser : Exception - " + ex.Message + ex.StackTrace);
            } 
        }

        /// <summary>
        /// 用户关注事件处理逻辑
        /// </summary>
        /// <param name="wechatEventHistory"></param>
        /// <param name="wechatInfo"></param>
        /// <param name="scanSource"></param>
        /// <returns></returns>
        private string SubscribeUser(MxApiWechatEventHistory wechatEventHistory, MxApiWechatInfo wechatInfo,
            int scanSource)
        {
#if DEBUG
            _fileLog.Info("MkysController | SubscribeUser | Begin - " + wechatEventHistory.Event);
#endif
            //构建用于处理下发用户消息的信息参数实体
            var weChatMsgRev = new MxApiWeChatMsgRev
            {
                WechatInfoId = wechatInfo.Id,
                FromUserName = wechatEventHistory.FromUserName,
                Content = scanSource == 0 ? "event_subscribe" : "event_scan",
                MsgType = scanSource == 0 ? "event_subscribe" : "event_scan"
            };

            try
            {
                var wechatUserResult =
                    MatrixCloudCenterInterFuncBllObj.SyncWechatUserFullInfoFromWechatToMatrixCloud(
                        wechatEventHistory.FromUserName, CurrentMatrixCloudProjectInfo.PjMcId,
                        CurrentMatrixCloudProjectInfo.PjSecret);
                _fileLog.Info(JsonTool.ObjToJson(wechatUserResult));
                if (!wechatUserResult.Status)
                {
                    _fileLog.Info(
                        "MkysController | SubscribeUser | SyncWechatUserFullInfoFromWechatToMatrixCloud error - " +
                        wechatUserResult.Message);
                    var resultAutoReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 0,
                        CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                    if (resultAutoReply.Status && string.IsNullOrWhiteSpace(resultAutoReply.Data))
                    {
                        return resultAutoReply.Data;
                    }
                    return string.Empty;
                }

                if (wechatUserResult.StatusCode == 1)
                {
#if DEBUG
                _fileLog.Info("MkysController | SubscribeUser | Add and sync user info to matrix cloud");
#endif
                }

                #region 扫描带参数的二维码关注  获取参数二维码绑定的商家后台用户ID，并添加消费者用户信息
                var strMsgFromAddCusumer = AddNewConsumerrInfo(wechatEventHistory, wechatUserResult.Data);
                if (!string.IsNullOrWhiteSpace(strMsgFromAddCusumer))
                {
                    return strMsgFromAddCusumer;
                }
                #endregion
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysController | SubscribeUser : Exception - " + ex.Message + ex.StackTrace);
            }

            var resultReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 1,
                        CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
            if (resultReply.Status && !string.IsNullOrWhiteSpace(resultReply.Data))
            {
                return resultReply.Data;
            }
            return string.Empty;
        }

        /// <summary>
        /// 添加用户记录并根据情况发送一张优惠券
        /// </summary>
        /// <param name="wechatEventHistory"></param>
        /// <param name="wechatUserInfo"></param>
        private string AddNewConsumerrInfo(MxApiWechatEventHistory wechatEventHistory, MxApiWechatUser wechatUserInfo)
        {
            var strRet = string.Empty;
            try
            {
                var nShopAccountId = 0;
                var nShopId = 0;
                if (!string.IsNullOrWhiteSpace(wechatEventHistory.Ticket))
                {
                    var weChatParamQrCodeResult =
                        MatrixCloudCenterInterFuncBllObj.GetParamQrCodeByWechatTiket(wechatEventHistory.Ticket,
                            CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                    if (weChatParamQrCodeResult.Status && weChatParamQrCodeResult.Data != null &&
                        weChatParamQrCodeResult.Data.Id > 0)
                    {
                        var mcAccountsBll = new McAccountsBLL();
                        var mcAccount = mcAccountsBll.GetModelByParamQrCodeId(weChatParamQrCodeResult.Data.Id, CurrentMatrixCloudProjectInfo);
                        if (mcAccount != null && mcAccount.Id > 0)
                        {
                            nShopAccountId = mcAccount.Id;
                            nShopId = mcAccount.ShopId;
                        }  
                    }
                }

                var nConsumerId = AddNewConusmerInfo(wechatUserInfo, nShopAccountId, nShopId);
                _fileLog.Info("nShopId:" + nShopId + "___nShopAccountId:" + nShopAccountId + "___nConsumerId:" + nConsumerId + "___Ticket:" + wechatEventHistory.Ticket);
                if (nConsumerId > 0)
                {
                    var strMkysApiHost = ConfigurationManager.AppSettings["MkysApiHost"];
                    if (!string.IsNullOrWhiteSpace(strMkysApiHost) && nShopId > 0)
                    {
                        //发送优惠券
                        var strMkysVoucherApiUrl = strMkysApiHost +
                                                   "/api/CloudCardApi/FixedQrCodeDraw?openId={0}&encryptSId={1}&mcId={2}&longitude={3}&latitude={4}&verifyCode={5}";
                        var strEncryptShopId = EncryptionLib.Encrypt(nShopId.ToString());
                        var strVerifyCode = EncryptionLib.Encrypt(wechatUserInfo.OpenId + strEncryptShopId + CurrentMatrixCloudProjectInfo.PjMcId + "" + "" );
                        strMkysVoucherApiUrl = string.Format(strMkysVoucherApiUrl, wechatUserInfo.OpenId,
                            strEncryptShopId, CurrentMatrixCloudProjectInfo.PjMcId, string.Empty, string.Empty,
                            strVerifyCode);

                        var strResultJson = HttpClientHelper.PostResponse(strMkysVoucherApiUrl, string.Empty);
                        if (!string.IsNullOrWhiteSpace(strResultJson))
                        {
                            var resultObj = JsonTool.JsonToObj<Result<List<CloudCards>>>(strResultJson);
                            if (resultObj != null && resultObj.Status)
                            {
                                var weChatMsgRev = new MxApiWeChatMsgRev
                                {
                                    WechatInfoId = wechatUserInfo.WechatInfoId,
                                    FromUserName = wechatEventHistory.FromUserName,
                                    Content = "event_subscribeVoucher",
                                    MsgType = "event_subscribeVoucher"
                                };
                                var resultReply = MatrixCloudCenterInterFuncBllObj.GetMsgRobotWorkReply(weChatMsgRev, 1,
                                    CurrentMatrixCloudProjectInfo.PjMcId, CurrentMatrixCloudProjectInfo.PjSecret);
                                if (resultReply.Status && !string.IsNullOrWhiteSpace(resultReply.Data))
                                {
                                    return resultReply.Data;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _fileLog.Error("MkysController | AddNewCustomerInfo : Exception - " + ex.Message + ex.StackTrace);
            }

            return strRet;
        }

        /// <summary>
        /// 添加消费者信息
        /// </summary>\
        /// <param name="wechatUserInfo"></param>
        /// <param name="shopAccountId"></param>
        /// <param name="shopId"></param>
        private int AddNewConusmerInfo(MxApiWechatUser wechatUserInfo, int shopAccountId = 0, int shopId = 0)
        {
            var nConsumerId = 0;
            var consumerBll = new ConsumerBLL();
            var consumerInfo = consumerBll.GetConsumerInfoByMxWechatInfoUserId(wechatUserInfo.WiuId);
            var localProjectInfo =
                MatrixCloudProjectInfoBLL.Instance.GetModelByPjMcId(CurrentMatrixCloudProjectInfo.PjMcId);
            if (localProjectInfo == null || localProjectInfo.Id == 0)
            {
                return 0;
            }
            if (consumerInfo == null || consumerInfo.Id == 0)
            {
                var newConsumer = new Consumer
                {
                    MxProjectInfoId = localProjectInfo.Id,
                    MxWechatInfoUserId = wechatUserInfo.WiuId,
                    Avatar = wechatUserInfo.Headimgurl,
                    NickName = wechatUserInfo.NickName,
                    RealName = wechatUserInfo.RealName,
                    Mobile = wechatUserInfo.Mobile,
                    Sex = int.Parse(wechatUserInfo.Sex),
                    RegTime = DateTime.Now,
                    IpAddress = IpHelper.IPAddress,
                    ShopAccountId = shopAccountId,
                    ShopId = shopId,
                    Birth = Convert.ToDateTime("1970-01-01 00:00:00"),
                    IsDelete = false
                };

                nConsumerId = consumerBll.Add(newConsumer);

#if DEBUG
                _fileLog.Info("MkysController | AddNewConusmerInfo | Add consumer user info - " + wechatUserInfo.OpenId +
                              ", consumer id - " + nConsumerId);
#endif
            }
            else
            {
                consumerInfo.NickName = wechatUserInfo.NickName;
                consumerInfo.Mobile = wechatUserInfo.Mobile;
                consumerInfo.Sex = int.Parse(wechatUserInfo.Sex);
                consumerInfo.Avatar = wechatUserInfo.Headimgurl;
                consumerBll.Update(consumerInfo);

                nConsumerId = consumerInfo.Id;
                if (consumerInfo.ShopId == 0 && consumerInfo.ShopAccountId == 0)
                {
                    //if (shopId == 3480)
                    //{
                    //    consumerInfo.ShopAccountId = shopAccountId;
                    //    consumerInfo.ShopId = shopId;
                    //    consumerBll.Update(consumerInfo);
                    //}
#if DEBUG
                _fileLog.Info("MkysController | AddNewConusmerInfo | Update consumer user info - " + wechatUserInfo.OpenId +
                              ", consumer id - " + consumerInfo.Id);
#endif
                }
            }
            return nConsumerId;
        }

        #endregion
    }
}
